﻿var OrderDetails = {
    options: {
        orderId: null,
        getItemsInOrderUrl: "/OrdersStation/Orders/GetItemsInOrder/",
        deleteItemsInOrderUrl: "/OrdersStation/Orders/DeleteItemsInOrder/"
    },

    Init: function (opts) {
        this.options =
            $.extend(
                this.options,
                opts);

        $.ajax({
            url: this.options.getItemsInOrderUrl,
            type: "post",
            data: { orderId: this.options.orderId }
        }).done(function (items) {
            OrderDetails.reloadList(items);
        });
    },

    reloadList: function (itemList) {
        var orderDetails = $("#orderDetails");
        orderDetails.html("");

        var isEnglishRegex = new RegExp("^[a-zA-Z]+", "gim");
        for (var itmIndex in itemList) {
            var item = itemList[itmIndex];
            var dir = "direction:";
            if (isEnglishRegex.test(item.name)) {
                dir += "ltr";
            }
            else {
                dir += "rtl";
            }
            var li =
                $("<li data-id=" + item.itemInOrderId + ">" + item.name + " (" + item.quantity + ")<a href='#' style='" + dir + "'>X</a></li>");
            orderDetails.append(li);
        }

        orderDetails.find("li").click(function () {
            var clickedElement = this;
            $.ajax({
                url: OrderDetails.options.deleteItemsInOrderUrl,
                type: "post",
                data: { itemInOrderId: $(this).data("id") }
            }).done(function (res) {
                clickedElement.parentNode.removeChild(clickedElement);
            });
        });
    }
};